package com.carrental.crm.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.carrental.common.exception.BusinessException;
import com.carrental.crm.dto.UserCouponDTO;
import com.carrental.crm.entity.Coupon;
import com.carrental.crm.entity.UserCoupon;
import com.carrental.crm.mapper.UserCouponMapper;
import com.carrental.crm.service.CouponService;
import com.carrental.crm.service.UserCouponService;
import com.carrental.crm.vo.CouponVO;
import com.carrental.crm.vo.UserCouponVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * 用户优惠券服务实现类
 */
@Service
public class UserCouponServiceImpl extends ServiceImpl<UserCouponMapper, UserCoupon> implements UserCouponService {

    @Autowired
    private CouponService couponService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long issueCouponToUser(UserCouponDTO userCouponDTO) {
        // 检查优惠券是否存在
        Coupon coupon = couponService.getById(userCouponDTO.getCouponId());
        if (coupon == null) {
            throw new BusinessException("优惠券不存在");
        }
        
        // 检查优惠券状态
        if (coupon.getStatus() != 1 && coupon.getStatus() != 2) {
            throw new BusinessException("优惠券状态不允许发放");
        }
        
        // 检查优惠券是否过期
        LocalDateTime now = LocalDateTime.now();
        if (coupon.getEndTime().isBefore(now)) {
            throw new BusinessException("优惠券已过期");
        }
        
        // 创建用户优惠券实体
        UserCoupon userCoupon = new UserCoupon();
        BeanUtils.copyProperties(userCouponDTO, userCoupon);
        
        // 设置默认值
        if (userCoupon.getStatus() == null) {
            userCoupon.setStatus(1); // 默认未使用状态
        }
        
        // 生成优惠券码
        if (StringUtils.isBlank(userCoupon.getCouponCode())) {
            userCoupon.setCouponCode(generateCouponCode());
        }
        
        userCoupon.setReceiveTime(LocalDateTime.now());
        userCoupon.setCreateTime(LocalDateTime.now());
        userCoupon.setUpdateTime(LocalDateTime.now());
        
        // 保存用户优惠券信息
        save(userCoupon);
        
        // 增加优惠券发放数量
        couponService.incrementIssueCount(coupon.getId(), 1);
        
        return userCoupon.getId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean batchIssueCoupon(Long couponId, List<Long> userIds) {
        if (couponId == null || userIds == null || userIds.isEmpty()) {
            throw new BusinessException("参数不正确");
        }
        
        // 检查优惠券是否存在
        Coupon coupon = couponService.getById(couponId);
        if (coupon == null) {
            throw new BusinessException("优惠券不存在");
        }
        
        // 检查优惠券状态
        if (coupon.getStatus() != 1 && coupon.getStatus() != 2) {
            throw new BusinessException("优惠券状态不允许发放");
        }
        
        // 检查优惠券是否过期
        LocalDateTime now = LocalDateTime.now();
        if (coupon.getEndTime().isBefore(now)) {
            throw new BusinessException("优惠券已过期");
        }
        
        // 批量创建用户优惠券
        List<UserCoupon> userCouponList = new ArrayList<>();
        for (Long userId : userIds) {
            UserCoupon userCoupon = new UserCoupon();
            userCoupon.setUserId(userId);
            userCoupon.setCouponId(couponId);
            userCoupon.setCouponCode(generateCouponCode());
            userCoupon.setStatus(1); // 未使用
            userCoupon.setReceiveTime(now);
            userCoupon.setStartTime(coupon.getStartTime());
            userCoupon.setEndTime(coupon.getEndTime());
            userCoupon.setCreateTime(now);
            userCoupon.setUpdateTime(now);
            
            userCouponList.add(userCoupon);
        }
        
        // 批量保存用户优惠券
        boolean result = saveBatch(userCouponList);
        
        // 增加优惠券发放数量
        if (result) {
            couponService.incrementIssueCount(couponId, userIds.size());
        }
        
        return result;
    }

    @Override
    public UserCouponVO getUserCouponById(Long id) {
        UserCoupon userCoupon = getById(id);
        if (userCoupon == null) {
            return null;
        }
        return convertToVO(userCoupon);
    }

    @Override
    public UserCouponVO getUserCouponByCode(String couponCode) {
        if (StringUtils.isBlank(couponCode)) {
            throw new BusinessException("优惠券码不能为空");
        }
        
        LambdaQueryWrapper<UserCoupon> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserCoupon::getCouponCode, couponCode);
        
        UserCoupon userCoupon = getOne(queryWrapper);
        if (userCoupon == null) {
            return null;
        }
        
        return convertToVO(userCoupon);
    }

    @Override
    public Page<UserCouponVO> pageUserCoupons(Long userId, Integer status, Page<UserCoupon> page) {
        if (userId == null) {
            throw new BusinessException("用户ID不能为空");
        }
        
        LambdaQueryWrapper<UserCoupon> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserCoupon::getUserId, userId);
        
        if (status != null) {
            queryWrapper.eq(UserCoupon::getStatus, status);
        }
        
        // 按创建时间降序排序
        queryWrapper.orderByDesc(UserCoupon::getCreateTime);
        
        Page<UserCoupon> userCouponPage = page(page, queryWrapper);
        return convertToVOPage(userCouponPage);
    }

    @Override
    public Page<UserCouponVO> pageAllUserCoupons(Page<UserCoupon> page, Long userId, Long couponId, String couponCode, Integer status, String startTime, String endTime) {
        LambdaQueryWrapper<UserCoupon> queryWrapper = new LambdaQueryWrapper<>();
        
        // 添加查询条件
        if (userId != null) {
            queryWrapper.eq(UserCoupon::getUserId, userId);
        }
        if (couponId != null) {
            queryWrapper.eq(UserCoupon::getCouponId, couponId);
        }
        if (StringUtils.isNotBlank(couponCode)) {
            queryWrapper.eq(UserCoupon::getCouponCode, couponCode);
        }
        if (status != null) {
            queryWrapper.eq(UserCoupon::getStatus, status);
        }
        
        // 处理时间范围
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        if (StringUtils.isNotBlank(startTime)) {
            LocalDateTime startDateTime = LocalDateTime.parse(startTime, formatter);
            queryWrapper.ge(UserCoupon::getCreateTime, startDateTime);
        }
        if (StringUtils.isNotBlank(endTime)) {
            LocalDateTime endDateTime = LocalDateTime.parse(endTime, formatter);
            queryWrapper.le(UserCoupon::getCreateTime, endDateTime);
        }
        
        // 按创建时间降序排序
        queryWrapper.orderByDesc(UserCoupon::getCreateTime);
        
        // 执行分页查询
        Page<UserCoupon> userCouponPage = page(page, queryWrapper);
        return convertToVOPage(userCouponPage);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean useCoupon(Long id, Long orderId, String orderNo) {
        if (id == null || orderId == null || StringUtils.isBlank(orderNo)) {
            throw new BusinessException("参数不能为空");
        }
        
        UserCoupon userCoupon = getById(id);
        if (userCoupon == null) {
            throw new BusinessException("用户优惠券不存在");
        }
        
        // 检查优惠券状态
        if (userCoupon.getStatus() != 1) {
            throw new BusinessException("优惠券状态不允许使用");
        }
        
        // 检查优惠券是否过期
        LocalDateTime now = LocalDateTime.now();
        if (userCoupon.getEndTime().isBefore(now)) {
            userCoupon.setStatus(3); // 已过期
            updateById(userCoupon);
            throw new BusinessException("优惠券已过期");
        }
        
        // 更新用户优惠券信息
        userCoupon.setStatus(2); // 已使用
        userCoupon.setOrderId(orderId);
        userCoupon.setOrderNo(orderNo);
        userCoupon.setUseTime(now);
        userCoupon.setUpdateTime(now);
        
        boolean result = updateById(userCoupon);
        
        // 增加优惠券使用数量
        if (result) {
            couponService.incrementUsedCount(userCoupon.getCouponId());
        }
        
        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean cancelUseCoupon(Long id) {
        if (id == null) {
            throw new BusinessException("用户优惠券ID不能为空");
        }
        
        UserCoupon userCoupon = getById(id);
        if (userCoupon == null) {
            throw new BusinessException("用户优惠券不存在");
        }
        
        // 检查优惠券状态
        if (userCoupon.getStatus() != 2) {
            throw new BusinessException("优惠券状态不允许取消使用");
        }
        
        // 检查优惠券是否过期
        LocalDateTime now = LocalDateTime.now();
        if (userCoupon.getEndTime().isBefore(now)) {
            userCoupon.setStatus(3); // 已过期
            updateById(userCoupon);
            throw new BusinessException("优惠券已过期");
        }
        
        // 更新用户优惠券信息
        userCoupon.setStatus(1); // 未使用
        userCoupon.setOrderId(null);
        userCoupon.setOrderNo(null);
        userCoupon.setUseTime(null);
        userCoupon.setUpdateTime(now);
        
        return updateById(userCoupon);
    }

    @Override
    public boolean checkCouponAvailable(Long id, Long vehicleId, Long storeId, Double amount) {
        if (id == null) {
            return false;
        }
        
        UserCoupon userCoupon = getById(id);
        if (userCoupon == null) {
            return false;
        }
        
        // 检查优惠券状态
        if (userCoupon.getStatus() != 1) {
            return false;
        }
        
        // 检查优惠券是否过期
        LocalDateTime now = LocalDateTime.now();
        if (userCoupon.getEndTime().isBefore(now)) {
            userCoupon.setStatus(3); // 已过期
            updateById(userCoupon);
            return false;
        }
        
        // 获取优惠券信息
        Coupon coupon = couponService.getById(userCoupon.getCouponId());
        if (coupon == null) {
            return false;
        }
        
        // 检查金额条件
        if (coupon.getThreshold() != null && amount < coupon.getThreshold().doubleValue()) {
            return false;
        }
        
        // 检查车型条件
        if (StringUtils.isNotBlank(coupon.getApplicableVehicles()) && vehicleId != null) {
            List<String> vehicleIds = Arrays.asList(coupon.getApplicableVehicles().split(","));
            if (!vehicleIds.contains(vehicleId.toString())) {
                return false;
            }
        }
        
        // 检查门店条件
        if (StringUtils.isNotBlank(coupon.getApplicableStores()) && storeId != null) {
            List<String> storeIds = Arrays.asList(coupon.getApplicableStores().split(","));
            if (!storeIds.contains(storeId.toString())) {
                return false;
            }
        }
        
        return true;
    }

    @Override
    public List<UserCouponVO> getUserAvailableCoupons(Long userId, Long vehicleId, Long storeId, Double amount) {
        if (userId == null) {
            throw new BusinessException("用户ID不能为空");
        }
        
        LocalDateTime now = LocalDateTime.now();
        
        // 查询用户未使用的优惠券
        LambdaQueryWrapper<UserCoupon> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserCoupon::getUserId, userId)
                .eq(UserCoupon::getStatus, 1) // 未使用
                .le(UserCoupon::getStartTime, now)
                .ge(UserCoupon::getEndTime, now)
                .orderByDesc(UserCoupon::getCreateTime);
        
        List<UserCoupon> userCouponList = list(queryWrapper);
        if (userCouponList.isEmpty()) {
            return new ArrayList<>();
        }
        
        // 获取优惠券ID列表
        List<Long> couponIds = userCouponList.stream()
                .map(UserCoupon::getCouponId)
                .collect(Collectors.toList());
        
        // 查询优惠券信息
        List<Coupon> couponList = couponService.listByIds(couponIds);
        
        // 过滤符合条件的优惠券
        List<UserCouponVO> availableCoupons = new ArrayList<>();
        for (UserCoupon userCoupon : userCouponList) {
            // 获取对应的优惠券
            Coupon coupon = couponList.stream()
                    .filter(c -> c.getId().equals(userCoupon.getCouponId()))
                    .findFirst()
                    .orElse(null);
            
            if (coupon == null) {
                continue;
            }
            
            // 检查金额条件
            if (coupon.getThreshold() != null && amount < coupon.getThreshold().doubleValue()) {
                continue;
            }
            
            // 检查车型条件
            if (StringUtils.isNotBlank(coupon.getApplicableVehicles()) && vehicleId != null) {
                List<String> vehicleIds = Arrays.asList(coupon.getApplicableVehicles().split(","));
                if (!vehicleIds.contains(vehicleId.toString())) {
                    continue;
                }
            }
            
            // 检查门店条件
            if (StringUtils.isNotBlank(coupon.getApplicableStores()) && storeId != null) {
                List<String> storeIds = Arrays.asList(coupon.getApplicableStores().split(","));
                if (!storeIds.contains(storeId.toString())) {
                    continue;
                }
            }
            
            // 添加到可用优惠券列表
            UserCouponVO vo = convertToVO(userCoupon);
            
            // 设置优惠券信息
            vo.setCouponName(coupon.getName());
            vo.setCouponType(coupon.getType());
            
            // 设置优惠券类型名称
            if (coupon.getType() != null) {
                switch (coupon.getType()) {
                    case 1:
                        vo.setCouponTypeName("满减券");
                        break;
                    case 2:
                        vo.setCouponTypeName("折扣券");
                        break;
                    case 3:
                        vo.setCouponTypeName("直减券");
                        break;
                    default:
                        vo.setCouponTypeName("未知");
                }
            }
            
            // 设置优惠金额/折扣率/门槛
            vo.setAmount(coupon.getAmount() != null ? coupon.getAmount().toString() : null);
            vo.setDiscountRate(coupon.getDiscountRate() != null ? coupon.getDiscountRate().toString() : null);
            vo.setThreshold(coupon.getThreshold() != null ? coupon.getThreshold().toString() : null);
            
            availableCoupons.add(vo);
        }
        
        return availableCoupons;
    }

    /**
     * 生成优惠券码
     *
     * @return 优惠券码
     */
    private String generateCouponCode() {
        return UUID.randomUUID().toString().replace("-", "").substring(0, 16).toUpperCase();
    }

    /**
     * 将用户优惠券实体转换为VO
     *
     * @param userCoupon 用户优惠券实体
     * @return 用户优惠券VO
     */
    private UserCouponVO convertToVO(UserCoupon userCoupon) {
        if (userCoupon == null) {
            return null;
        }
        
        UserCouponVO vo = new UserCouponVO();
        BeanUtils.copyProperties(userCoupon, vo);
        
        // 获取优惠券信息
        Coupon coupon = couponService.getById(userCoupon.getCouponId());
        if (coupon != null) {
            vo.setCouponName(coupon.getName());
            vo.setCouponType(coupon.getType());
            
            // 设置优惠券类型名称
            if (coupon.getType() != null) {
                switch (coupon.getType()) {
                    case 1:
                        vo.setCouponTypeName("满减券");
                        break;
                    case 2:
                        vo.setCouponTypeName("折扣券");
                        break;
                    case 3:
                        vo.setCouponTypeName("直减券");
                        break;
                    default:
                        vo.setCouponTypeName("未知");
                }
            }
            
            // 设置优惠金额/折扣率/门槛
            vo.setAmount(coupon.getAmount() != null ? coupon.getAmount().toString() : null);
            vo.setDiscountRate(coupon.getDiscountRate() != null ? coupon.getDiscountRate().toString() : null);
            vo.setThreshold(coupon.getThreshold() != null ? coupon.getThreshold().toString() : null);
        }
        
        // 设置状态名称
        if (userCoupon.getStatus() != null) {
            switch (userCoupon.getStatus()) {
                case 1:
                    vo.setStatusName("未使用");
                    break;
                case 2:
                    vo.setStatusName("已使用");
                    break;
                case 3:
                    vo.setStatusName("已过期");
                    break;
                default:
                    vo.setStatusName("未知");
            }
        }
        
        return vo;
    }

    /**
     * 将用户优惠券分页数据转换为VO分页
     *
     * @param page 用户优惠券分页
     * @return 用户优惠券VO分页
     */
    private Page<UserCouponVO> convertToVOPage(Page<UserCoupon> page) {
        Page<UserCouponVO> voPage = new Page<>();
        BeanUtils.copyProperties(page, voPage, "records");
        
        List<UserCouponVO> voList = new ArrayList<>();
        for (UserCoupon userCoupon : page.getRecords()) {
            voList.add(convertToVO(userCoupon));
        }
        voPage.setRecords(voList);
        
        return voPage;
    }
} 